<template>
  <fy-table
    :table-data="currentPageData"
    :columns="columns"
    title="完整功能表格"
    selection="multiple"
    :pagination="pagination"
    :loading="loading"
    row-key="name"
    :rows-per-page-options="[5, 10, 20, 50]"
    @request="onRequest"
    v-model:selected="selected"
  >
    <template #loading>
      <q-inner-loading showing color="primary" />
    </template>
    <template #top-right>
      <q-btn-group>
        <q-btn color="primary" label="新增" icon="add" @click="onAdd" />
        <q-btn
          color="negative"
          label="批量删除"
          icon="delete"
          :disable="!selected.length"
          @click="onDelete"
        />
      </q-btn-group>
    </template>

    <!-- 可选：自定义操作按钮 -->
    <template #body-cell-actions="{ row }">
      <q-btn flat round color="primary" icon="edit" @click.stop="handleEdit(row)">
        <q-tooltip>编辑</q-tooltip>
      </q-btn>
      <q-btn
        flat
        round
        color="negative"
        icon="delete"
        @click.stop="handleDelete(row)"
        :disable="row.status === '进行中'"
      >
        <q-tooltip>删除</q-tooltip>
      </q-btn>
    </template>
  </fy-table>
</template>

<script setup>
import { ref } from 'vue'
import FyTable from 'components/common/FyTable/index.vue'
import { useQuasar } from 'quasar'
import { formatToThousands } from '@/utils/formate.js'

const q = useQuasar()
const selected = ref([])
const loading = ref(false)

// 定义静态数据
const staticData = [
  {
    id: 1,
    name: '高端办公椅',
    price: 1299.99,
    ROUTE_INFO:
      '[{"STARTCITY":"泰州市","ENDCITY":"苏州市","STARTDATE":"2025-03-03"},{"STARTCITY":"泰州市","ENDCITY":"上海市","STARTDATE":"2025-03-03"}]',
    amount: 12999.9,
    stock: 50,
    status: '在售',
  },
  {
    id: 2,
    name: '人体工学键盘',
    price: 899.0,
    ROUTE_INFO:
      '[{"STARTCITY":"泰州市","ENDCITY":"苏州市","STARTDATE":"2025-03-03"},{"STARTCITY":"泰州市","ENDCITY":"上海市","STARTDATE":"2025-03-03"}]',
    amount: 8990.0,
    stock: 30,
    status: '在售',
  },
  {
    id: 3,
    name: '4K显示器',
    price: 2499.0,
    ROUTE_INFO:
      '[{"STARTCITY":"泰州市","ENDCITY":"苏州市","STARTDATE":"2025-03-03"},{"STARTCITY":"泰州市","ENDCITY":"上海市","STARTDATE":"2025-03-03"}]',
    amount: 24990.0,
    stock: 0,
    status: '缺货',
  },
  {
    id: 4,
    name: '无线鼠标',
    price: 299.0,
    ROUTE_INFO:
      '[{"STARTCITY":"泰州市","ENDCITY":"苏州市","STARTDATE":"2025-03-03"},{"STARTCITY":"泰州市","ENDCITY":"上海市","STARTDATE":"2025-03-03"}]',
    amount: 2990.0,
    stock: 100,
    status: '在售',
  },
  {
    id: 5,
    name: '笔记本电脑',
    price: 6999.0,
    ROUTE_INFO:
      '[{"STARTCITY":"泰州市","ENDCITY":"苏州市","STARTDATE":"2025-03-03"},{"STARTCITY":"泰州市","ENDCITY":"上海市","STARTDATE":"2025-03-03"}]',
    amount: 69990.0,
    stock: 15,
    status: '在售',
  },
  {
    id: 6,
    name: '移动硬盘',
    price: 499.0,
    ROUTE_INFO:
      '[{"STARTCITY":"泰州市","ENDCITY":"苏州市","STARTDATE":"2025-03-03"},{"STARTCITY":"泰州市","ENDCITY":"上海市","STARTDATE":"2025-03-03"}]',
    amount: 4990.0,
    stock: 0,
    status: '缺货',
  },
  {
    id: 7,
    name: '机械键盘',
    price: 799.0,
    ROUTE_INFO:
      '[{"STARTCITY":"泰州市","ENDCITY":"苏州市","STARTDATE":"2025-03-03"},{"STARTCITY":"泰州市","ENDCITY":"上海市","STARTDATE":"2025-03-03"}]',
    amount: 7990.0,
    stock: 45,
    status: '在售',
  },
]

// 当前页数据
const currentPageData = ref([])

const pagination = ref({
  sortBy: 'name',
  descending: false,
  page: 1,
  rowsPerPage: 10,
  rowsNumber: staticData.length,
})

// 修改列定义，添加金额字段
const columns = [
  {
    name: 'name',
    label: '产品名称',
    field: 'name',
    align: 'left',
    sortable: true,
  },
  {
    name: 'price',
    label: '价格',
    field: 'price',
    align: 'right',
    sortable: true,
    format: (val) => `¥${formatToThousands(val)}`,
  },
  {
    name: 'ROUTE_INFO',
    label: '起始城市',
    field: 'ROUTE_INFO',
    align: 'left',
    sortable: false,
    format: (val) => {
      if (!val) return '无数据'
      try {
        const routes = JSON.parse(val)
        return routes[0]?.STARTCITY || '无数据'
      } catch (e) {
        console.error('解析 ROUTE_INFO 失败:', e)
        return '无效数据'
      }
    },
  },
  {
    name: 'amount',
    label: '金额',
    field: 'amount',
    align: 'right',
    sortable: true,
    format: (val) => `¥${formatToThousands(val)}`,
  },
  {
    name: 'stock',
    label: '库存',
    field: 'stock',
    align: 'right',
    sortable: true,
  },
  {
    name: 'status',
    label: '状态',
    field: 'status',
    align: 'center',
  },
  {
    name: 'actions',
    label: '操作',
    field: 'actions',
    align: 'center',
  },
]

// 修改请求处理函数
const onRequest = async (props) => {
  const { page, rowsPerPage, sortBy, descending } = props.pagination
  loading.value = true

  try {
    await new Promise((resolve) => setTimeout(resolve, 300)) // 模拟加载延迟

    let data = [...staticData]

    // 排序处理
    if (sortBy) {
      data.sort((a, b) => {
        let x = descending ? b[sortBy] : a[sortBy]
        let y = descending ? a[sortBy] : b[sortBy]
        return x > y ? 1 : x < y ? -1 : 0
      })
    }

    // 分页处理
    const start = (page - 1) * rowsPerPage
    const end = Math.min(start + rowsPerPage, data.length)
    currentPageData.value = data.slice(start, end)

    // 更新分页信息
    pagination.value = {
      ...props.pagination,
      rowsNumber: data.length,
    }
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化加载
onRequest({
  pagination: pagination.value,
})

// 处理编辑
const handleEdit = (row) => {
  q.notify({
    message: `编辑记录：${row.name}`,
    color: 'primary',
  })
}

// 处理删除
const handleDelete = (row) => {
  q.notify({
    message: `删除记录：${row.name}`,
    color: 'negative',
  })
}

// 处理批量删除
const onDelete = () => {
  console.log(selected.value)
  // q.notify({
  //   message: `将要删除 ${selected.value.length} 条记录`,
  //   color: 'negative',
  // })
}

// 处理新增
const onAdd = () => {
  q.notify({
    message: '点击了新增按钮',
    color: 'primary',
  })
}
</script>
